package com.youmans.eduservice.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youmans.commonutils.R;
import com.youmans.eduservice.entity.EduTeacher;
import com.youmans.eduservice.entity.vo.TeacherQuery;
import com.youmans.eduservice.service.EduTeacherService;
import com.youmans.servicebase.exceptionHandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 * 讲师 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-04-29
 */
@Api(tags = "教师控制器")
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {
    @Autowired
    private EduTeacherService eduTeacherService ;

    //根据方法对其返回结果进行缓存，下次请求时，如果缓存存在，
    // 则直接读取缓存数据返回；如果缓存不存在，则执行方法，
    // 并把返回的结果存入缓存中。一般用在查询方法上
    @Cacheable(value = "sellect",key = "'selectAllTeacher'")
    @ApiOperation("获取所有教师")
    @GetMapping("findAll")
    public R findAllTeacher(){
        List<EduTeacher> list = eduTeacherService.list(null);
        return R.ok().data("items",list) ;
    }

    //使用该注解标志的方法，会清空指定的缓存。一般用在更新或者删除方法上
    @CacheEvict(value = "teacher",key = "'selectPageList'")
    @ApiOperation("逻辑删除讲师")
    @DeleteMapping("{id}")
    public R removeTheacher(@ApiParam("讲师ID") @PathVariable String id){
        boolean flag = eduTeacherService.removeById(id);
        return flag?R.ok():R.error();
    }

    @Cacheable(value = "teacher",key = "'selectTeacherPage'")
    @ApiOperation("分页查询讲师")
    @GetMapping("pageTeacher/{pageNum}/{pageSize}")
    public R getTeachers(
            @ApiParam("分页查询的页码数")@PathVariable("pageNum") Integer pageNum,
            @ApiParam("分页查询的记录数")@PathVariable("pageSize") Integer pageSize
            //@ApiParam("查询条件") EduTeacher eduTeacher
    ){
        //        分页带条件查询
        Page<EduTeacher> pageTeacher = new Page<>(pageNum, pageSize);
//        通过服务层
        eduTeacherService.page(pageTeacher,null);
        long total = pageTeacher.getTotal();//总记录数
        List<EduTeacher> records = pageTeacher.getRecords();//数据list集合
//        封装result对象并返回
        LinkedHashMap map = new LinkedHashMap() ;
        map.put("total",total) ;
        map.put("rows",records) ;
        return R.ok().data(map) ;
//        return R.ok().data("total",total).data("rows",records);
    }


    /*

        //4 条件查询带分页的方法
    @PostMapping("pageTeacherCondition/{current}/{limit}")
    public R pageTeacherCondition(@PathVariable long current,@PathVariable long limit,
                                  @RequestBody(required = false) TeacherQuery teacherQuery) {
        //创建page对象
        Page<EduTeacher> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String name = teacherQuery.getName();
        Integer level = teacherQuery.getLevel();
        String begin = teacherQuery.getBegin();
        String end = teacherQuery.getEnd();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(name)) {
            //构建条件
            try {
                wrapper.like("name", URLDecoder.decode(name,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if(!StringUtils.isEmpty(level)) {
            wrapper.eq("level",level);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("gmt_create",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("gmt_create",end);
        }

        //调用方法实现条件查询分页
        eduTeacherService.page(pageTeacher,wrapper);

        long total = pageTeacher.getTotal();//总记录数
        List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
        return R.ok().data("total",total).data("rows",records);
    }

    */


//    @Cacheable(value = "teacher",key = "'selectCondition'")
    @ApiOperation("分页查询讲师带条件")
    @PostMapping("pageTeacherCondition/{pageNum}/{pageSize}")//required = false表示参数可以为空
    public R getTeachersCondition(
            @ApiParam(value = "分页查询的页码数",defaultValue = "1")@PathVariable("pageNum") Integer pageNum,
            @ApiParam(value = "分页查询的记录数",defaultValue = "3")@PathVariable("pageSize") Integer pageSize,
            @ApiParam("查询条件")@RequestBody(required = false) TeacherQuery teacherQuery
    ){
        //        分页带条件查询
        Page<EduTeacher> pageTeacher = new Page<>(pageNum, pageSize);
        IPage<EduTeacher> gradeIPage = null ;
        if(!StringUtils.isEmpty(teacherQuery)){
            //        通过服务层
            gradeIPage = eduTeacherService.pageCondition(pageTeacher,teacherQuery);
        }else{
//            QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
//            wrapper.orderByDesc("gmt_create");
//            gradeIPage = eduTeacherService.page(pageTeacher,wrapper);
            gradeIPage = eduTeacherService.page(pageNum, pageSize);

        }


        long total = gradeIPage.getTotal();//总记录数
        List<EduTeacher> records = gradeIPage.getRecords();//数据list集合
//        封装result对象并返回
        LinkedHashMap map = new LinkedHashMap() ;
        map.put("total",total) ;
        map.put("rows",records) ;
        return R.ok().data(map) ;
//        return R.ok().data("total",total).data("rows",records);
    }

    //使用该注解标志的方法，每次都会执行，
    // 并将结果存入指定的缓存中。
    // 其他方法可以直接从响应的缓存中读取缓存数据，
    // 而不需要再去查询数据库。一般用在新增方法上。
    @CachePut(value = "teacher")
    @ApiOperation("添加讲师的接口方法")
    @PostMapping("addTeacher")
    public R addTeacher(@RequestBody EduTeacher eduTeacher){
        boolean flag = eduTeacherService.save(eduTeacher);
        return flag?R.ok():R.error();
    }


    @ApiOperation("根据id查询讲师")
    @GetMapping("getTeacher/{id}")
    public R getTeacher(@PathVariable String id){
        EduTeacher eduTeacher = eduTeacherService.getById(id);
        try {
           // int i = 10 / 0;
        }catch (Exception e){
            throw new GuliException(20001,"执行自定义异常");
        }
        return R.ok().data("teacher",eduTeacher) ;
    }

    @CacheEvict(value = "teacher")
    @ApiOperation("修改讲师")
    @PostMapping("updateTeacher")
    public R updateTeacher(@RequestBody EduTeacher eduTeacher){
        return eduTeacherService.updateById(eduTeacher)?R.ok():R.error();
    }
}

